package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.ItemVO;
import com.hmall.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hmall.search.config.EsConstant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemSearchServiceImpl implements SearchService {

    @Autowired
    RestHighLevelClient client;

    @Override
    public List<String> Suggestionsd(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest(EsConstant.INDEX_NAME);
            request.source().sort("_score", SortOrder.DESC);


            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));

            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> filters(ItemVO params) {
        Map<String, List<String>> map = new HashMap<>();
        SearchRequest searchRequest = new SearchRequest(EsConstant.INDEX_NAME);

//        设置查询条件
        BoolQueryBuilder boolQueryBuilder = basicQuery(params);

        searchRequest.source().query(boolQueryBuilder);
//        设置聚合条件
        searchRequest.source().aggregation(
                AggregationBuilders.terms("brandAggs").field("brand").size(20)
        );
        searchRequest.source().aggregation(
                AggregationBuilders.terms("categoryAggs").field("category").size(20)
        );
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

//            获取聚合结果
            Aggregations aggregations = response.getAggregations();
            Terms brandAggs = aggregations.get("brandAggs");
            List<? extends Terms.Bucket> brandAggsBuckets = brandAggs.getBuckets();
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket brandAggsBucket : brandAggsBuckets) {
                String key = brandAggsBucket.getKeyAsString();
                brandList.add(key);
            }

            List<String> categoryList = new ArrayList<>();
            Terms categoryAggs = aggregations.get("categoryAggs");
            List<? extends Terms.Bucket> buckets = categoryAggs.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                String key = bucket.getKeyAsString();
                categoryList.add(key);
            }

            map.put("brand",brandList);
            map.put("category",categoryList);
            return  map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public PageDTO<ItemDoc> search(ItemVO params) {
        SearchRequest searchRequest = new SearchRequest(EsConstant.INDEX_NAME);

//        使用bool查询
        BoolQueryBuilder boolQueryBuilder = basicQuery(params);

//        设置查询条件
        searchRequest.source().query(boolQueryBuilder);
//        设置分页
        int index = (params.getPage()-1)*params.getSize();
        searchRequest.source().from(index);
        searchRequest.source().size(params.getSize());
//        设置排序
        String sortBy = params.getSortBy();
        if(sortBy.equals("sold")){
//              销量排序
            searchRequest.source().sort(sortBy, SortOrder.DESC);
        }else if(sortBy.equals("price")){
//            价格排序
            searchRequest.source().sort(sortBy, SortOrder.ASC);
        }


        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            long total = hits.getTotalHits().value;
            List<ItemDoc> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                String jsonStr = hit.getSourceAsString();
//                把json转对象
                ItemDoc itemDoc = JSON.parseObject(jsonStr, ItemDoc.class);
                list.add(itemDoc);
            }
            return new PageDTO<>(total,list);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    private BoolQueryBuilder basicQuery(ItemVO params) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if(StringUtils.isNotBlank(params.getKey())){
            boolQuery.must(QueryBuilders.matchQuery("all",params.getKey()).operator(Operator.AND));
        }else{
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
//        过滤条件
        if(StringUtils.isNotBlank(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        if(StringUtils.isNotBlank(params.getCategory())){
            boolQuery.filter(QueryBuilders.termQuery("category",params.getCategory()));
        }
        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if(minPrice!=null ){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gt(minPrice*100));
        }
        if (maxPrice!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lt(maxPrice*100));
        }
        return boolQuery;

    }

}
